<template>
  <div class="user-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索账号/昵称"
            clearable
            @clear="handleSearch"
          >
            <template #suffix>
              <el-icon class="el-input__icon" @click="handleSearch">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="roleFilter" placeholder="选择角色" clearable>
            <el-option label="管理员" value="ADMIN" />
            <el-option label="警察" value="POLICE" />
            <el-option label="用户" value="USER" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加用户
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 用户列表表格 -->
    <el-table 
    :data="filteredUserList" 
    style="width: 100%" 
    v-loading="loading"
    height="calc(100vh - 280px)">
      <el-table-column prop="uid" label="UID" width="80" />
      <el-table-column prop="username" label="账号" width="120" />
      <el-table-column prop="name" label="昵称" width="120" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="address" label="地址" width="180" />
      <el-table-column prop="avatar" label="头像" width="100">
        <template #default="scope">
          <el-image 
            v-if="scope.row.avatar"
            :src="scope.row.avatar" 
            style="width: 40px; height: 40px"
          />
          <span v-else>无头像</span>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色" width="100">
        <template #default="scope">
          <el-tag :type="getRoleType(scope.row.role)">
            {{ getRoleLabel(scope.row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" >
        <template #default="scope">
          {{formatDate(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button v-show="scope.row.uid!==useUserStore().getUserInfo().uid" type="danger" link @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form :model="userForm" label-width="100px" :rules="rules" ref="userFormRef">
        <el-form-item label="账号" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogType!=='add'"/>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="userForm.address" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleAvatarChange"
            accept="image/*"
          >
            <img v-if="previewImage" :src="previewImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="警察" value="POLICE" />
            <el-option label="用户" value="USER" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {getUserListByPageAPI, updateUserInfoAPI, addUserAPI, deleteUserByUidAPI, updateAvatarAPI} from "@/apis/user";
import {useUserStore} from "@/stores/user";


// 数据
const searchQuery = ref('')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const userFormRef = ref(null)

const userForm = ref({
  uid:'',
  username: '',
  password: '',
  name: '',
  phone: '',
  address: '',
  avatar: '',
  role: 'USER',
  status:1,
})

const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }

  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: false, message: '请输入电话', trigger: 'blur' },
    // { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: false, message: '请输入地址', trigger: 'blur' }
  ]
}

// 用户数据列表
const userList = ref([])

// 添加角色筛选的ref
const roleFilter = ref('')

// 更新筛选逻辑
const filteredUserList = computed(() => {
  let filtered = userList.value
  // 按搜索关键词筛选（账号和昵称）
  if (searchQuery.value) {
    const keyword = searchQuery.value
    filtered = filtered.filter(user => {
      return user.username.includes(keyword) || user.name!==null&&user.name.includes(keyword)
    })
  }
  // 按角色筛选
  if (roleFilter.value) {
    filtered = filtered.filter(user => user.role === roleFilter.value)
  }
  return filtered
})

// 方法
function handleAdd() {
  dialogType.value = 'add'
  userForm.value = {
    username: '',
    password: '',
    name: '',
    phone: '',
    address: '',
    avatar: '',
    role: 'USER'
  }
  dialogVisible.value = true
}

function handleEdit(row) {
  dialogType.value = 'edit'
  userForm.value = { ...row }
  previewImage.value=userForm.value.avatar
  dialogVisible.value = true
}

function handleDelete(row) {
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    // 实现删除逻辑
    await deleteUserByUidAPI(row.uid).then(res => {
      if(res.code==='200'){
        ElMessage.success('删除成功')
        getUserList()
      }else{
        ElMessage.error(res.msg)
      }
    })

  })
}

function handleStatusChange(row) {
  ElMessage.success(`用户状态已${row.status ? '启用' : '禁用'}`)
}

function handleSizeChange(val) {
  pageSize.value = val
  // 重新加载数据
}

function handleCurrentChange(val) {
  currentPage.value = val
  // 重新加载数据
}

// 添加新的响应式变量
const previewImage = ref('')
const imageFile = ref(null)

// 修改头像改变处理函数
function handleAvatarChange(file) {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }

  imageFile.value = file.raw
  previewImage.value = URL.createObjectURL(file.raw)
}

// 修改提交处理函数
async function handleSubmit() {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      // 如果有新的头像文件需要上传
      if (imageFile.value) {
        const formData = new FormData()
        formData.append('uid',userForm.value.uid)
        formData.append('file', imageFile.value)
        const uploadRes = await updateAvatarAPI(formData)
        
        if (uploadRes.code === '200') {
          userForm.value.avatar = uploadRes.data
        } else {
          ElMessage.error('头像上传失败')
          return
        }
      }

      let res
      if(dialogType.value === 'add'){
        res = await addUserAPI(userForm.value)
      }else if(dialogType.value === 'edit'){
        res = await updateUserInfoAPI(userForm.value)
      }
      
      if(res.code==='200'){
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
        getUserList()
        dialogVisible.value=false
        // 清理头像相关状态
        imageFile.value = null
        previewImage.value = ''
      }else{
        ElMessage.error(res.msg)
      }
    }
  })
}

function getRoleType(role) {
  const types = {
    'ADMIN': 'danger',
    'POLICE': 'warning',
    'USER': 'success'
  }
  return types[role] || 'info'
}

function getRoleLabel(role) {
  const labels = {
    'ADMIN': '管理员',
    'POLICE': '警察',
    'USER': '用户'
  }
  return labels[role] || '未知'
}

async function getUserList() {
  const res = await getUserListByPageAPI(pageSize.value, currentPage.value)
  if(res.code==='200'){
    userList.value=res.data.list
    total.value=res.data.total
  }
}

function formatDate(date) {
  const target=new Date(date)
  return `${target.toLocaleDateString()}`+` ${target.toLocaleTimeString()}`
}

watch(pageSize,()=>{
  getUserList()
})

watch(currentPage,()=>{
  getUserList()
})

onMounted(() => {
  // 加载初始数据
  getUserList()
})
</script>

<style scoped>
.user-management {
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.operation-area {
  flex-shrink: 0;
  margin-bottom: 20px;
}

.table-container {
  flex: 1;
  overflow: hidden;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
</style>
